package com.hgx.lc.core.facade;

import cn.hutool.core.util.RandomUtil;
import com.hgx.su.common.pure.dto.*;
import com.hgx.su.common.pure.exception.AppException;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * Rest接口demo示例
 *
 * @author HGX
 * @since: 2020-12-16 09:03
 */
@RestController
@RequestMapping("/")
public class RestDemoController {

    /**
     * excel文件
     */
    public static final String EXCEL_CONTENT_TYPE = "application/vnd.ms-excel;charset=utf-8";

    /**
     * 普通的文本
     */
    public static final String TEXT_CONTENT_TYPE = "application/octet-stream;charset=utf-8";


    /**
     * 输入单个数据->输出单个数据[POST]
     *
     * @param paramRequest 入参
     * @return 返回
     */
    @PostMapping("outOneByOne")
    public ResultResponse<OnePackageDto<Long>> outOneByOne(@RequestBody ParamRequest<OnePackageDto<Long>> paramRequest) {
        return ResultResponse.ok(paramRequest.getBody().getData());
    }

    /**
     * 发生AppException接口
     *
     * @param paramRequest 入参
     * @return 返回
     */
    @PostMapping("outAppExceptionOneByOne")
    public ResultResponse<OnePackageDto<Long>> outAppExceptionOneByOne(@RequestBody ParamRequest<OnePackageDto<Long>> paramRequest) {
        throw new AppException("1001", "0001", "发生了一个AppException异常");
    }

    /**
     * 发生ArithmeticException异常接口
     *
     * @param paramRequest 入参
     * @return 返回
     */
    @PostMapping("outExceptionOneByOne")
    public ResultResponse<OnePackageDto<Long>> outExceptionOneByOne(@RequestBody ParamRequest<OnePackageDto<Long>> paramRequest) {
        int i = 0;
        int j = 1;

        int i1 = j / i;
        return ResultResponse.ok(paramRequest.getBody().getData());
    }

    /**
     * 输入空数据->输出空数据[POST]
     *
     * @return 返回数据
     */
    @PostMapping("outNull")
    public ResultResponse<NullClassDto> outNull(@RequestBody ParamRequest<NullClassDto> paramRequest) {
        return ResultResponse.ok(paramRequest.getBody());
    }

    /**
     * 输入空数据->直接输出空数据[POST]
     *
     * @return 返回数据
     */
    @PostMapping("directOutNull")
    @SuppressWarnings("unused")
    public ResultResponse<NullClassDto> directOutNull(@RequestBody ParamRequest<NullClassDto> paramRequest) {
        return ResultResponse.ok();
    }


    /**
     * 输入对象数据->输出对象数据[POST]
     *
     * @return 返回数据
     */
    @PostMapping("outObjByObj")
    public ResultResponse<GeneralCodeNameDto> outObjByObj(@RequestBody ParamRequest<GeneralCodeNameDto> paramRequest) {

        return ResultResponse.ok(paramRequest.getBody());
    }


    /**
     * 输入列表数据->输出列表数据[POST]
     *
     * @return 返回数据
     */
    @PostMapping("outListByList")
    public ResultResponse<ListPackageDto<GeneralCodeNameDto>> outListByList(@RequestBody ParamRequest<ListPackageDto<GeneralCodeNameDto>> paramRequest) {

        List<GeneralCodeNameDto> list = paramRequest.getBody().getList();

        return ResultResponse.ok(list);
    }


    /**
     * 上传单个文件
     *
     * @param reqId 请求id
     * @param file  文件
     * @return res
     */
    @PostMapping("/upload")
    public ResultResponse<NullClassDto> upload(@RequestParam("reqId") String reqId, @RequestParam("file") MultipartFile file) {
        return ResultResponse.ok();
    }

    /**
     * 批量上传文件
     *
     * @param file 文件
     * @return res
     */
    @PostMapping("/batchUpload")
    public ResultResponse<NullClassDto> batchFileUpload(MultipartFile[] file) {
        return ResultResponse.ok();
    }


    /**
     * 下载普通文件文件
     *
     * @param response res
     * @throws IOException 异常
     * @download
     */
    @PostMapping("download")
    public void download(HttpServletResponse response, @RequestBody ParamRequest<NullClassDto> paramRequest) throws IOException {
        String randomStr = RandomUtil.randomNumbers(50);
        String fileName = "test.log";
        //要使用smart-doc debug页面测试文件下载，则必须设置filename响应头，否则请采用其他模拟工具测试。
        // urlDecode用于处理中文件名
        response.setHeader("filename", urlEncode(fileName));
        ServletOutputStream outputStream = downloadText(fileName, response);
        outputStream.write(randomStr.getBytes());
    }

    public String urlEncode(String str) {
        if (str == null) {
            return null;
        } else {
            try {
                return java.net.URLEncoder.encode(str, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                return null;
            }
        }
    }


    /**
     * 基础的文件下载
     *
     * @param contentType 下载文件的类型
     * @param fileName    文件名称
     * @param response    response
     * @return 返回
     * @throws IOException 异常
     */
    protected ServletOutputStream baseDownload(String contentType, String fileName, HttpServletResponse response)
            throws IOException {
        response.setContentType(contentType);
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename="
                + new String(fileName.getBytes("gbk"), StandardCharsets.ISO_8859_1));
        return response.getOutputStream();
    }

    /**
     * 文件下载
     *
     * @param fileName 下载文件
     * @param response 响应
     * @return ServletOutputStream
     * @throws IOException 异常
     */
    protected ServletOutputStream downloadText(String fileName, HttpServletResponse response) throws IOException {
        return baseDownload(TEXT_CONTENT_TYPE, fileName, response);
    }

    /**
     * 导出excel,添加文件名时需要自己添加后缀
     *
     * @param fileName 文件名(用户信息表.xls)
     * @param response HttpServletResponse
     * @return ServletOutputStream
     * @throws IOException 异常
     */
    @SuppressWarnings("unused")
    protected ServletOutputStream exportExcel(String fileName, HttpServletResponse response) throws IOException {
        return baseDownload(EXCEL_CONTENT_TYPE, fileName, response);
    }


}
